package com.lyt.springboot.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


//@Component
//@Order(2)
public class FilterTest implements Filter {

    /**
     * init方法，初始化过滤器，可以在init()方法中完成与构造方法类似的初始化功能，
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        System.out.println("FilterTest过滤器成功初始化。。。。。。。。。。。。。");
    }

    /**
     * 过滤器初始化后并在请求到达后端且进入到注册过滤器设置的匹配路径时回调。
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        //这里为了使用getHeader方法获取token，转型成HttpServletRequest
        System.out.println("FilterTest过滤器");
        System.out.println("token:"+req.getHeader("token"));
        String token = req.getHeader("token");
        //再判断token是否正确
        if(null==token){
            throw new RuntimeException("token为空");
        }
        //调用doFilter方法，正常返回servletResponse
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 过滤器销毁时回调。
     */
    @Override
    public void destroy() {
        Filter.super.destroy();
        System.out.println("FilterTest过滤器被销毁");
    }
}
